package com.qnw.CardGroupManagement;
import android.content.*;
import android.graphics.*;
import android.graphics.drawable.*;
import android.net.*;
import android.os.*;
import android.support.v4.util.*;
import android.support.v4.widget.*;
import android.support.v7.app.*;
import android.support.v7.widget.*;
import android.util.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import android.widget.AdapterView.*;
import com.google.zxing.*;
import com.google.zxing.common.*;
import com.google.zxing.qrcode.*;
import com.qnw.CardGroupManagement.adapter.*;
import com.qnw.CardGroupManagement.bean.*;
import com.qnw.CardGroupManagement.management.*;
import com.ygo.feihua.*;
import com.ygo.feihua.adapter.*;
import com.ygo.feihua.util.*;
import java.io.*;
import java.util.*;

import android.support.v4.util.ArrayMap;
import android.support.v7.widget.Toolbar;
import android.view.View.OnClickListener;
import com.qnw.CardGroupManagement.util.*;
import android.support.v4.app.*;
import com.xiaomi.mistatistic.sdk.*;

public class CgmaZhuye extends Fragment implements SwipeRefreshLayout.OnRefreshListener
{

	@Override
	public void onRefresh()
	{
		getType();
		deckTypeAdp.sx();
		allsx();
		zy_sw.setRefreshing(false);
		// TODO: Implement this method
	}
	

	private Gongju gj;
	private DialogUtils du;
	private ListView zy_list;
	private Spinner zy_fl;
	private Button zy_addfl;
	KzlistManagement kzm;
	List<Deck> data;
	
	List<DeckType> type;
	AdapterKzlist adpkz;
	DeckTypeAdapter deckTypeAdp;;
	
	SwipeRefreshLayout zy_sw;
	
	Handler handle=new Handler(){

		@Override
		public void handleMessage(Message msg)
		{
			// TODO: Implement this method
			super.handleMessage(msg);
			switch(msg.what){
				case 0:
					du.dis();
					break;
				case 1:
					du.dis();
					gj.show("解析卡组成功");				
					allsx();
					Intent i=new Intent(getActivity(), A4.class);
					i.putExtra("path", SharedPreferenceUtil.getYgopath()+"deck/"+msg.obj+".ydk");
					i.putExtra("name", (String)msg.obj);
					startActivity(i);				
					break;
				case 2:
					du.dis();
					gj.show("解析二维码成功但创建卡组失败,原因为"+msg.obj);
					break;
				case 3:
					du.dis();
					gj.show("该二维码不是卡组二维码");
					break;
				case 4:
					du.dis();
					gj.show("未在图中找到二维码");
					break;							
			}
		}

	};
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		
		View v=inflater.inflate(R.layout.cgma_zhuye,null);
		initView(v);
		
		zy_list.setOnItemClickListener(new OnItemClickListener(){

				@Override
				public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
				{
					Intent i=new Intent(getActivity(), A4.class);
					i.putExtra("path", data.get(p3).getPath());
					i.putExtra("name", data.get(p3).getName());
					startActivity(i);
					// TODO: Implement this method
				}
			});

		zy_list.setOnItemLongClickListener(new OnItemLongClickListener(){

				@Override
				public boolean onItemLongClick(AdapterView<?> p1, View p2, final int p33, long p4)
				{
					ListView li=(ListView) du.dialogl(true,data.get(p33).getName(),new String[]{"编辑","重命名","移动","分享","删除"});
					li.setOnItemClickListener(new OnItemClickListener(){

							@Override
							public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
							{
								du.dis();
								switch (p3){
									case 0:
										if(gj.isygo()){
											IntentUtil.deckEditIntent(getActivity(),data.get(p33).getPath());
										}
										break;
									case 1:
										View[] v=du.dialoge(false,"","重命名");
										final EditText ed=(EditText) v[0];
										Button bb=(Button) v[1];

										ed.setText(data.get(p33).getName());
										bb.setOnClickListener(new OnClickListener(){

												@Override
												public void onClick(View p1)
												{
													String na=ed.getText().toString().trim();
													if(na.equals("")){
														gj.show("卡组名不能为空");
													}else{
														if(FileUtil.cmm(data.get(p33).getPath(),na)){

															gj.show("重命名成功");
															allsx();
														}else{
															gj.show("重命名失败");
														}
														du.dis();
													}

													// TODO: Implement this method
												}
											});

										break;
									case 2:
										String[] s2=new String[type.size()-1];
										s2[0]="ygo";
										for(int i=0;i<s2.length;i++){
											if(i!=0){
												s2[i]=type.get(i+1).getName();
											}
										}

										ListView l2=(ListView) du.dialogl(true,"移动到",s2);
										l2.setOnItemClickListener(new OnItemClickListener(){

												@Override
												public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
												{

													if (p3 == 0) {
														if ((new File(data.get(p33).getPath()).getParent() + "/").equals(SharedPreferenceUtil.getYgopath() + "deck/")) {
															gj.show("不能移动到当前目录");
														} else {
															du.dis();
															try {
																FileUtil.moveFile(data.get(p33).getPath(), SharedPreferenceUtil.getYgopath() + "deck/", false);
																gj.show("移动成功");
																allsx();
															} catch (IOException e) {
																gj.show("移动失败,原因为" + e);
															}
														}
													} else {
														if ((new File(data.get(p33).getPath()).getParent() + "/").equals(type.get(p3 + 1).getPath())) {
															gj.show("不能移动到当前目录");
														} else {
															du.dis();
															try {
																FileUtil.moveFile(data.get(p33).getPath(), type.get(p3 + 1).getPath(), false);
																gj.show("移动成功");
																allsx();

															} catch (IOException e) {
																gj.show("移动失败");
															}
														}
													}
													// TODO: Implement this method
												}
											});
										break;
									case 3:

										du.dialogj1(false,"","生成图片中,请稍等");
										new Thread(new Runnable(){

												@Override
												public void run()
												{
													final File f=new File(data.get(p33).getPath());
													String aa="#ourygo_#"+data.get(p33).getName()+"_";
													try{
														BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(f)));
														String line="";

														for (;(line = reader.readLine()) != null;)
														{
															aa += line +"_";
														}
													}
													catch (IOException e)
													{}
													
													Bitmap bt=null;
													try {  
														aa="http://ourygo.top/html/deck.html?message="+WenBase64.urlBase64Code(aa, "utf-8");		
													Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
													hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
													
														QRCodeWriter writer = new QRCodeWriter();  
														// MultiFormatWriter writer = new MultiFormatWriter();  
														BitMatrix matrix = writer.encode(aa, BarcodeFormat.QR_CODE,zy_list.getWidth(),zy_list.getWidth(),hints);  
														bt=A4.bitMatrix2Bitmap(matrix);
													} catch (Exception e) {  
														Log.e("生成二维码错误","错误为"+e);
													}  

													//二维码中心图标
													//Bitmap  bmp = BitmapFactory.decodeResource( CgmaZhuye.this.getResources(),R.drawable.ourygo);
													// QRCodeEncoder.syncEncodeQRCode(aa,zy_list.getWidth(),Color.parseColor("#008cf9"),bmp);
													Message me=new Message();
													me.obj=bt;
													me.what=0;
													handle.sendMessage(me);

													String strDlgTitle = "分享"+data.get(p33).getName();
													String strSubject="";
													String strContent="";
													// 图片文件路径（SD卡根目录下“1.png”图片）
													try {
														String imgPath =Gongju.saveBitmap(bt, Gongju.PATH_EZ_MANAGEMENT + "ydk_fenxiang/", data.get(p33).getName());
														// 图片URI
														Uri imageUri = Uri.fromFile(new File(imgPath));
														// 分享
														gj.ydkfx(strDlgTitle, strSubject, strContent, imageUri);
														
													} catch (IOException e) {
														gj.show("分享失败,原因为"+e);
													}
													

													// TODO: Implement this method
												}
											}).start();
										break;
									case 4:
										View[] v4=du.dialogt(true,data.get(p33).getPath(),"确定要删除这个卡组嘛？");
										Button b41,b42;
										b41=(Button) v4[0];
										b42=(Button) v4[1];
										b41.setText("取消");
										b42.setText("删除");
										b41.setOnClickListener(new OnClickListener(){

												@Override
												public void onClick(View p1)
												{
													du.dis();
													// TODO: Implement this method
												}
											});
										b42.setOnClickListener(new OnClickListener(){

												@Override
												public void onClick(View p1)
												{if(FileUtil.delFile(data.get(p33).getPath())){
														gj.show("删除成功");
														data.remove(p33);
														allsx();
													}else{
														gj.show("删除失败");
													}
													du.dis();
													// TODO: Implement this method
												}
											});

										break;
								}

								// TODO: Implement this method
							}
						});

					// TODO: Implement this method
					return true;
				}
			});



		zy_fl.setOnItemSelectedListener(new OnItemSelectedListener(){

				@Override
				public void onItemSelected(AdapterView<?> p1, View p2, int p3, long p4)
				{

					if(p3==0){
						allsx();
					}else{
						data.clear();
						File_ydk.clear();
						String s=type.get(p3).getPath();
						String[] sss1=File_ydk.ydkname(s);
						String[] ydkpa1=File_ydk.ydkpath(s);
						for(int i=0;i<ydkpa1.length;i++){

							Deck d=new Deck();
							d.setName(sss1[i]);
							d.setPath(ydkpa1[i]);
							d.setType(type.get(p3));

							data.add(d);
						}
						adpkz.sx();
					}

					// TODO: Implement this method
				}

				@Override
				public void onNothingSelected(AdapterView<?> p1)
				{
					// TODO: Implement this method
				}
			});
		zy_addfl.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1)
				{
					View[] v=du.dialoge(false,"","请输入分类名");
					final EditText ed=(EditText) v[0];
					Button b=(Button) v[1];

					b.setOnClickListener(new OnClickListener(){

							@Override
							public void onClick(View p1)
							{
								String na=ed.getText().toString().trim();
								if(na.equals("")){
									gj.show("分类名不能为空");
								}else{

									File ff=new File(Gongju.PATH_EZ_MANAGEMENT+"type/"+na+"/");

									if(ff.isDirectory()){
										gj.show("该分类已存在");

									}else{
										ff.mkdir();

										DeckType dt=new DeckType();
										dt.setName(na);
										dt.setPath(ff.toString());
										type.add(dt);

										deckTypeAdp.sx();
										allsx();
										du.dis();
										gj.show("创建成功");
									}

								}

								// TODO: Implement this method
							}
						});
					// TODO: Implement this method
				}
			});
		
		
		// TODO: Implement this method
		return v;
	}
	

	@Override
	public void onResume(){
		// TODO: Implement this method
		super.onResume();
		MiStatInterface.recordPageStart(getActivity(), "卡组列表");
	}

	@Override
	public void onPause(){
		// TODO: Implement this method
		super.onPause();
		MiStatInterface.recordPageEnd();
	}
	
	
	private void allsx(){
		data.clear();
		for(DeckType ma:type){
			if(ma.getPath()!=null){
				String s=ma.getPath();
				File_ydk.clear();
				String[] sss1=File_ydk.ydkname(s);
				String[] ydkpa1=File_ydk.ydkpath(s);
				for(int i=0;i<ydkpa1.length;i++){
					Deck d=new Deck();
					d.setName(sss1[i]);
					d.setPath(ydkpa1[i]+"/");
					d.setType(ma);
					data.add(d);
				}
			}
		}
		adpkz.sx();
	}
	
	public static void getType(){
		
		KzlistManagement kzl=KzlistManagement.getdx();
		kzl.getType().clear();
		
		DeckType dt=new DeckType();
		dt.setPath(null);
		dt.setName("全部");
		kzl.getType().add(dt);
	
		DeckType dt1=new DeckType();
		dt1.setPath(SharedPreferenceUtil.getYgopath() + "deck/");
		dt1.setName("ygo");
		kzl.getType().add(dt1);

		for (String s:FileUtil.getFolder(Gongju.PATH_EZ_MANAGEMENT + "type/")){
			
			String[] ss=s.split("/");
			DeckType dts=new DeckType();
			dts.setName(ss[ss.length - 1]);
			dts.setPath(s+"/");
			kzl.getType().add(dts);
		}
	}
	
	
	
	private void initView(View v){
		zy_list=(ListView)v.findViewById(R.id.zy_list);
		zy_fl=(Spinner)v.findViewById(R.id.zy_fl);
		zy_addfl=(Button)v.findViewById(R.id.zy_addfl);
		zy_sw=(SwipeRefreshLayout)v.findViewById(R.id.zy_sw);
		
		gj=Gongju.getdx(getActivity());
		du=DialogUtils.getdx(getActivity());
		kzm=KzlistManagement.getdx();
		data=kzm.getDeck();
		type=kzm.getType();
		
		adpkz=new AdapterKzlist(getActivity(),data);
		zy_list.setAdapter(adpkz);
		deckTypeAdp =new DeckTypeAdapter(getActivity(),type);
		
		zy_fl.setAdapter(deckTypeAdp);
		
		zy_sw.setColorSchemeResources(R.color.colorMain);
		zy_sw.setOnRefreshListener(this);
		//手动调用,通知系统去测量
        zy_sw.measure(0,0);
		zy_sw.setRefreshing(true);
		onRefresh();
	}
	
	public void ParsingDeck(final String img_url){
		if(!img_url.equals("")){
			du.dialogj1(false,"","解析中,请稍等");
			new Thread(new Runnable(){

					@Override
					public void run()
					{
						Drawable drawable=Drawable.createFromPath(img_url);				
						String s = QRCodeUtils.getStringFromQRCode(drawable);

						
						
						if (s != null){
							String u="http://ourygo.top/html/deck.html?message=";
							
							try
							{
								s=WenBase64.urlBase64Decode(s.substring(u.length(), s.length()), "utf-8");
							}
							catch (UnsupportedEncodingException e)
							{}
							String[] ss=s.split("_");
							if(ss[0].indexOf("#ourygo")!=-1){
								String sx = "";
								for(int i=0;i<ss.length;i++){
									if(i!=0&&i!=1){
										if(i==ss.length-1){
											sx+=ss[i];
										}else{
											sx+=ss[i]+"\n";
										}

									}
								}
								try
								{
									FileOutputStream fos=new FileOutputStream(SharedPreferenceUtil.getYgopath()+"deck/"+ss[1].substring(1,ss[1].length())+".ydk");
									fos.write(sx.getBytes());
									fos.close();
									Message me=new Message();
									me.what=1;
									me.obj=ss[1].substring(1,ss[1].length());
									handle.sendMessage(me);
								}
								catch (IOException e)
								{
									Message me=new Message();
									me.what=2;
									me.obj=e;
									handle.sendMessage(me);
								}
							}else{
								handle.sendEmptyMessage(3);
							}
						}else{
							handle.sendEmptyMessage(4);
						}

						// TODO: Implement this method
					}
				}).start();

		}
	}
	
	
}
